import Vue from 'vue'
import VueRouter from 'vue-router'
import RegisterView from '@/views/RegisterView.vue'
import LogonView from '@/views/LogonView.vue'



Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'RegisterView',
    meta: {
      title: '注册'
    },
    component:RegisterView,
  },
  {
    path: '/login',
    name: 'LogonView',
    meta: {
      title: '登录'
    },
    component:LogonView,
  },
  {
    path: '/home',
    name: 'HomeView',
    meta: {
      is: true,
      title: '首页'
    },
    component: () => import('@/views/HomeView.vue')
  },
  //错误页面
  {
    path: '*',
    name: 'ErrorPage',
    component: () => import('@/views/ErrorView.vue')
  }
]

const router = new VueRouter({
  routes
})

//全局前置守卫
//路由守卫
router.beforeEach((to, from, next) => {
  console.log(to)
  console.log(from);
  if (to.meta.is) {
    if (JSON.parse(localStorage.getItem('user'))) {
      next()
    } else {
      Vue.prototype.$message.error('请先登录');
        next('/login')
    }
  }
  
  next()
})

router.afterEach((to, from) => {
  console.log(to, from);
  document.title = to.meta.title || 'Vue'
})

export default router
